package com.hengpeng.msls.controller;

import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.itfinbase.constants.RespCodeConstants;
import com.hengpeng.itfinbase.constants.TransCodeConstants;
import com.hengpeng.itfinbase.en.ActivityType;
import com.hengpeng.itfinbase.message.ResponseMessage;
import com.hengpeng.itfinbase.message.activity.InviteSendRedPacketRequest;
import com.hengpeng.itfinbase.message.activity.UnfreeRedPacketRequest;
import com.hengpeng.itfinbase.message.userInfo.UserInfoRegisterRequest;
import com.hengpeng.itfinbase.message.userInfo.UserInfoResponse;
import com.hengpeng.itfinbase.persist.UserInfo;
import com.hengpeng.itfinbase.persist.UserInfo.RegisterSource;
import com.hengpeng.itfinbase.persist.UserInfo.UserInfoType;
import com.hengpeng.itfinbase.persist.VerifyCode.VerifyType;
import com.hengpeng.msls.config.Configuration;
import com.hengpeng.msls.constants.LSConstants;
import com.hengpeng.msls.tools.PatternUtils;
import com.hengpeng.msls.vo.SessionMember;

/**
 * html5注册控制器 lugaofei 20151104
 *
 */
@Controller
public class RegisterController extends BaseController {
    /**
     * <pre>
     * 注册
     * </pre>
     * 
     * @param request
     * @param username
     * @param password
     * @param mobile
     * @param recommendCode
     * @param resp
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/register")
    @ResponseBody
    public ServiceResult<String> register(HttpServletRequest request, String username, String password, String mobile,
            String recommendCode, String mobilecode, HttpServletResponse resp, String checkcode) throws Exception {
        /*String isCan = ConfigUtil.getParameter("permissions.regedit");
        if (isCan.equalsIgnoreCase("false")) {
            return validateFailure(ConfigUtil.getParameter("permissions.regedit.disabled.des"));
        }*/
        if (checkcode == null || checkcode.equals("")) {
            return validateFailure("请输入图片验证码");
        }
        String vcode = (String) request.getSession().getAttribute("vcode");
        String wanneng = Configuration.getValue("itfints.validate.code");

        boolean isValidate = false;
        if (wanneng == null) {
            isValidate = checkcode.equals(vcode);
        } else {
            isValidate = checkcode.equals(vcode) || wanneng.equals(checkcode);
        }
        if (!isValidate) {
            return validateFailure("图形验证码错误");
        }

        int pleng = password.length();

        if (pleng < 6 || pleng > 16) {
            return validateFailure("密码字符长度应为6-16之间");
        }
        if (mobile == null) {
            return validateFailure("手机号码不能为空");
        } else {
            if (!PatternUtils.MOBILE_PATTERN.matcher(mobile).matches()) {
                return validateFailure("手机号码格式不正确");
            }
        }
        List<UserInfo> user = serviceFactory.getUserInfoService().getUserInfoByMone(mobile);
        if (user != null && user.size() > 0) {
            return validateFailure("手机号码已经存在");
        }
        if (StringUtils.isEmpty(mobilecode)) {
            return validateFailure("短信验证码不能为空");
        }

        UserInfoRegisterRequest registerDto = new UserInfoRegisterRequest();
        registerDto.setVerifyCode(mobilecode);
        registerDto.setMobile(mobile);
        registerDto.setPassword(password);
        registerDto.setUsername(mobile);
        registerDto.setUserIpAddress(request.getRemoteAddr());
        registerDto.setType(UserInfoType.PERSON);
        registerDto.setRegisterSource(RegisterSource.WEB);
        registerDto.setRecommendCode(recommendCode);
        registerDto.setTransType(TransCodeConstants.MemberTransCode.MEMBER_REGISTER);
        UserInfoResponse response = (UserInfoResponse) serviceFactory.getProtFactory().remoteTrans(registerDto);
        ServiceResult<String> sr = getServiceResult(response, null);
        if (!sr.getIsSuccess()) {
            request.getSession().removeAttribute("vcode");
            return sr;
        }
        /**
         * 推荐码不为空则，注册成功调用邀请送红包活动接口,调用等级升级系统进行会员等级升级
         */
//        if (!StringHelper.isEmpty(recommendCode)) {
//            InviteSendRedPacketRequest inviteSendRedPacketRequest = new InviteSendRedPacketRequest();
//            inviteSendRedPacketRequest.setTransType(TransCodeConstants.ActivityTransCode.INVITE_SEND_REDPACKET);
//            inviteSendRedPacketRequest.setUserId(response.getUserInfo().getId());
//            inviteSendRedPacketRequest.setActivityType(ActivityType.INVITE_REDPACKET);
//            serviceFactory.getPortActiveFactory().remoteTrans(inviteSendRedPacketRequest);
            /**
             * 调用会员等级升级接口进行会员等级升级,暂不放开
             */
//            UserLevelUpRequest userLevelUpRequest = new UserLevelUpRequest();
//            userLevelUpRequest.setRecommendCode(recommendCode);
//            userLevelUpRequest.setTransType(TransCodeConstants.MemberTransCode.MEMBER_LEVEL_UP);
//            serviceFactory.getProtFactory().remoteTrans(userLevelUpRequest);
//        }
        /**
         * 注册成功查看是否有未激活的红包,如果有则激活
         */
        UnfreeRedPacketRequest unfreeRedPacketRequest = new UnfreeRedPacketRequest();
        unfreeRedPacketRequest.setTransType(TransCodeConstants.ActivityTransCode.UNFREE_REDPACKET);
        unfreeRedPacketRequest.setMobile(mobile);
        unfreeRedPacketRequest.setUserId(response.getUserInfo().getId());
        unfreeRedPacketRequest.setTrustAccountId(response.getUserInfo().getTrustAccountId());
        serviceFactory.getPortActiveFactory().remoteTrans(unfreeRedPacketRequest);
        
        SessionMember session = new SessionMember();
        session.setUser(response.getUserInfo());
        request.getSession().setAttribute(LSConstants.CLIENT_SESSION_MEMBER, session);
        return sr;
    }

    /**
     * 验证表单
     *//*
    @RequestMapping(value = "/checkform")
    @ResponseBody
    public ServiceResult<String> checkform(HttpServletRequest request, String password, String mobile,
            String recommendCode, HttpServletResponse resp, String checkcode) {
        
         * String isCan = ConfigUtil.getParameter("permissions.regedit"); if
         * (isCan.equalsIgnoreCase("false")) { return
         * validateFailure(ConfigUtil.
         * getParameter("permissions.regedit.disabled.des")); }
         
        if (checkcode == null || checkcode.equals("")) {
            return validateFailure("请输入图片验证码");
        }
        String vcode = (String) request.getSession().getAttribute("vcode");
        String wanneng = Configuration.getValue("itfints.validate.code");

        boolean isValidate = false;
        if (wanneng == null) {
            isValidate = checkcode.equals(vcode);
        } else {
            isValidate = checkcode.equals(vcode) || wanneng.equals(checkcode);
        }
        if (!isValidate) {
            return validateFailure("图形验证码错误");
        }

        int pleng = password.length();

        if (pleng < 6 || pleng > 16) {
            return validateFailure("密码字符长度应为6-16之间");
        }
        if (mobile == null) {
            return validateFailure("手机号码不能为空");
        } else {
            if (!PatternUtils.MOBILE_PATTERN.matcher(mobile).matches()) {
                return validateFailure("手机号码格式不正确");
            }
        }
        List<UserInfo> user = serviceFactory.getUserInfoService().getUserInfoByMone(mobile);
        if (user != null && user.size() > 0) {
            return validateFailure("手机号码已经存在");
        }
        ServiceResult<String> sr = new ServiceResult<String>();
        ServiceResult<Long> result = sendValidSMS(request, mobile);
        if (result.getIsSuccess()) {
            sr.setIsSuccess(true);
            sr.setCode("111");
        } else {
            sr.setIsSuccess(false);
            sr.setCode("999");
        }
        return sr;
    }*/

    /**
     * 手机验证发送短信(注册)
     * 
     * @return
     */
    @RequestMapping(value = "/sendRegValidSMS")
    @ResponseBody
    public ServiceResult<Long> sendValidSMS(HttpServletRequest request, String password, String mobile,
            String recommendCode, HttpServletResponse resp, String checkcode) {
        ServiceResult<Long> result = new ServiceResult<Long>();
        if (checkcode == null || checkcode.equals("")) {
            return validateFailure("请输入图片验证码");
        }
        String vcode = (String) request.getSession().getAttribute("vcode");
        String wanneng = Configuration.getValue("itfints.validate.code");

        boolean isValidate = false;
        if (wanneng == null) {
            isValidate = checkcode.equals(vcode);
        } else {
            isValidate = checkcode.equals(vcode) || wanneng.equals(checkcode);
        }
        if (!isValidate) {
            return validateFailure("图形验证码错误");
        }

        int pleng = password.length();

        if (pleng < 6 || pleng > 16) {
            return validateFailure("密码字符长度应为6-16之间");
        }
        if (mobile == null) {
            return validateFailure("手机号码不能为空");
        } else {
            if (!PatternUtils.MOBILE_PATTERN.matcher(mobile).matches()) {
                return validateFailure("手机号码格式不正确");
            }
        }
        List<UserInfo> user = serviceFactory.getUserInfoService().getUserInfoByMone(mobile);
        if (user != null && user.size() > 0) {
            return validateFailure("手机号码已经存在");
        }
        if (StringUtils.isEmpty(mobile)) {
            return validateFailure("参数为空");
        }
        Object sendTime = request.getSession().getAttribute("REGSMSTIME");
        long timeInterval = 30l;
        long nowTime = Calendar.getInstance().getTimeInMillis();
        if (sendTime == null) {
            request.getSession().setAttribute("REGSMSTIME", nowTime);
        } else {
            long countDown = nowTime - Long.parseLong(String.valueOf(sendTime));
            if (countDown >= 1000 * timeInterval) {
                request.getSession().setAttribute("REGSMSTIME", nowTime);
            } else {
                return validateFailure((timeInterval - countDown / 1000) + "s后，才能再次发送短信验证码");
            }
        }
        ResponseMessage response = serviceFactory.getUserInfoService().sendSMSForValidMobile(null, mobile, null,
                VerifyType.REGISTER);
        if (response != null) {
            if (RespCodeConstants.CommonCode.TRANS_SUC.equals(response.getRespCode())) {
                result.setIsSuccess(true);
                result.setMessage("已发送手机验证码");
                result.setReturnValue(timeInterval);
            } else {
                return validateFailure(response.getRespDesc());
            }
        } else {
            return validateFailure("发送手机验证码失败");
        }
        return result;
    }
    
    /**
     * 被邀请人点击邀请链接跳转到注册页
     */
    @RequestMapping(value = "/goregister")
    public String stepOne(HttpServletRequest request, String un, ModelMap map) {
        map.put("recommendCode", un);
        return "/user/register/index.jsp";
    }
}
